//模拟实现一个阻塞队列
//用数组实现
class MyBlockingQueue {
    private String[] data=null;
    private int head=0;
    private int tail=0;
    private int size=0;
    public MyBlockingQueue(int capacity){
        data=new String[capacity];
    }
    //实现put
    public void put(String elem) throws InterruptedException {

        synchronized(this){
            //1.判断队列是否为满,若为满，进行等待
            while(size== data.length){
                this.wait();
            }
            //2.进行放入元素
            data[tail]=elem;
            tail=(tail+1)%data.length;
            size++;
            this.notify();
        }

    }
    public String take() throws InterruptedException {
        synchronized(this){
            //1.判断队列是否为空，若为空，进行等待
           while (size==0){
                this.wait();
            }
            //2.进行取出元素
            String ret=data[head];
            head=(head+1)% data.length;
            size--;
            this.notify();
            return ret;
        }

    }

}

public class Demo37 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue=new MyBlockingQueue(100);
        Thread producer=new Thread(()->{
            int n=0;
            while(true){
                try {
                    myBlockingQueue.put(n+"");
                    System.out.println("生产元素:"+n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }


        },"producer");
        Thread consumer=new Thread(()->{
            String m=null;
            while(true){
                try {
                    m=myBlockingQueue.take();
                    System.out.println("消费元素"+m);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }


        },"consumer");
        producer.start();
        consumer.start();

    }
}